#include <stdio.h>
#include <iostream.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <windows.h>

#define snprintf   _snprintf 

#include "log.h"
#include "main.h"

cFileLog::cFileLog() {
	output = NULL;
}

cFileLog::cFileLog(char *path) throw(int) {
	int res;
	
	output = NULL;

	if ( (res = setPath(path)) != 0 )
		throw(res);
}

cFileLog::~cFileLog() {
	delete path;
	terminate(); // just to be sure
}

int cFileLog::setPath(char* newPath) {
	char *tmp;

	if (newPath == NULL)
		return EFAULT;

	tmp = new char[strlen(newPath) + 1];
	
	if( tmp == NULL )
		return errno;
	else
		path = tmp;
	
	strcpy(path,newPath);
	
	return 0;
}

const char *cFileLog::getPath() {
	return path;
}

// Opens the file and such
int cFileLog::initialize() {
	int res;
	
	if ( (res = terminate()) != 0)
		return res;

	output = fopen(path,"a");
	
	if ( output == NULL )
		return errno;
	
	return 0;
}

// Closes the file and such
int cFileLog::terminate() {
	if( output != NULL ) {
		fclose(output);
		output = NULL;
	}
		
	return 0;
}

// prints the time signature to the file
int cFileLog::printTimeSig() {
	SYSTEMTIME CurrentTime;
	GetSystemTime(&CurrentTime);
	
	char timeStr[DEF_STR_SIZE];
	snprintf(timeStr,DEF_STR_SIZE,"[%d-%d-%d--%d:%d:%d:%d] ",CurrentTime.wDay,	CurrentTime.wMonth,CurrentTime.wYear,CurrentTime.wHour,	CurrentTime.wMinute,CurrentTime.wSecond,CurrentTime.wMilliseconds);
	
	return printRaw(timeStr);
}

// prints the string as it is
int cFileLog::printRaw(char *msg, bool newLineFlag) {
	int res;

	if( (res=initialize()) != 0)
		return res;

	if( (res=fprintf(output,((newLineFlag)?"%s\n":"%s"),msg)) < 0) {
		terminate();
		return res;
	}

	return terminate();
}

int cFileLog::print(char *msg) {
	int res;

	if ( (res = printTimeSig()) != 0 )
		return res;
	
	return printNoSig(msg);
}

// print without the time signature
int cFileLog::printNoSig(char *msg) {
	return printRaw(msg,1);
}

// prints premeditated messages
int cFileLog::printStatus(int code, ...) {
	va_list args;
	char outMsg[DEF_STR_SIZE];
	
	va_start(args, code);
	
		// blocked cases to prevent arguments ambiguity
	switch(code) {
		case LOG_INVALID_HWND: {
			int arg1 = va_arg(args, int);

			snprintf(outMsg, DEF_STR_SIZE,"Invalid Window Handle %d", arg1);
			return print(outMsg);
			
			break;
	   }
		case LOG_NEW: {
			char *arg1 = va_arg(args,char*);
			int arg2 = va_arg(args,int);

			snprintf(outMsg, DEF_STR_SIZE,"Window opened with title = [%s]\tWindow Handle = [%d]",arg1, arg2);
			return print(outMsg);
			
			break;
		}
		default:
			return EINVAL;
	}

	return 0;
}
